<template>
    <div class="all-container flex_column" :class="{ horizontal: horizontal, full: !open }">
        <div class="fixed-header">
            <nav-bar :horizontal="horizontal" class="nav-user"></nav-bar>
            <tag-view v-if="tagShow" />
        </div>
        <div class="flex">
            <side-bar :class="['aside-container', !open && 'hide-bar']" :collapsed="open" />
            <div class="main-container" :class="{ hasTag: tagShow }">
                <setting />
                <scroll-bar class="app-main">
                    <bread-crumb v-if="showBreadcrumb" />
                    <router-view></router-view>
                    <back-top />
                </scroll-bar>
                <p class="company-info">{{ companyName }}</p>
            </div>
        </div>
    </div>
</template>

<script>
import { sideBar, navBar, tagView, setting, horizontalSide } from './components';
import backTop from '@/components/backTop/index';
import breadCrumb from './components/navBar/breadCrumb';
import { mapState } from 'vuex';
import { companyName } from '@/utils/config';

import mqtt from 'mqtt';
const moment = require('moment');

export default {
    name: 'layoutBox',
    components: { sideBar, navBar, tagView, setting, backTop, horizontalSide, breadCrumb },
    inject: ['playAudio'],
    data() {
        return {
            companyName,
            mtopic: 'realtime',
            // mtopic: '+/+',
            msg: '',
            client: {},
            websocket: null,
            currentPath: '',
            timer: null
        };
    },
    watch: {
        $route: {
            handler(to) {
                this.currentPath = to.path;
            },
            immediate: true
        },
        isAutoTheme: {
            handler(val) {
                this.changeTheme(val)
            },
            immediate: true
        }
    },
    created() {
        this.connectMqtt();
    },
    computed: {
        ...mapState({
            open: state => state.setting.open,
            showBar: state => state.setting.showBar,
            fixHeader: state => state.setting.fixHeader,
            tagShow: state => state.setting.tagShow,
            layout: state => state.setting.layout,
            initSetting: state => state.setting.initSetting,
            accountInfo: state => state.user.accountInfo,
            isAutoTheme: state => state.setting.isAutoTheme,
        }),
        horizontal() {
            return this.layout != 'vertical';
        },
        showBreadcrumb() {
            return this.currentPath != '/dashboard/index' && this.currentPath.indexOf('/map/index') == -1
        }
    },
    methods: {
        //处理自动化主题切换
        changeTheme(isAuto) {
            clearInterval(this.timer)
            if (isAuto) {
                this.swicthTheme();
                this.timer = setInterval(() => {
                    this.swicthTheme();
                }, 1000 * 60)
            }
        },
        swicthTheme(){
            let current = new Date().getTime();
            let today = moment(new Date()).format('YYYY-MM-DD');
            let night = new Date(today + ' 17:00:00').getTime();
            let morning = new Date(today + ' 06:00:00').getTime();
            let key = '';
            //暗黑
            if (current <= morning || current >= night) {
                key = 'dark'
            } else {
                key = 'blue'
            }
            this.$store.dispatch('setting/changeSetting', {
                key: 'theme',
                value: key,
                cache: 'THEME'
            });
            document.getElementsByTagName('body')[0].className = `vue-antd-admin-${key}Theme`;
        },
        changeVisivle() {
            this.$store.dispatch('setting/changeVisible', true);
        },
        //连接mqtt
        connectMqtt() {
            let time = new Date().getTime();
            let { userName, userId } = this.accountInfo;
            const options = {
                clean: true, // 保留回话
                connectTimeout: 4000, // 超时时间
                reconnectPeriod: 4000, // 重连时间间隔
                //clientId,这个是EMQ Dashboard的上的clientId 对应就好
                clientId: userName + '-' + time,
                username: 'admin',
                password: 'chen1988'
            };
            
            this.client = mqtt.connect(`ws://36.26.76.196:8083/mqtt`, options);
            this.client.on(
                'connect',
                e => {
                    this.client.subscribe(`schemeMessage/${userId}`, err => {
                        if (!err) {
                            console.log('订阅成功:任务通知主题');
                        }
                    });
                    this.client.subscribe(`alarmMessage/${userId}`, err => {
                        if (!err) {
                            console.log('订阅成功:报警消息');
                        }
                    });
                    this.client.subscribe(`normalMessage/${userId}`, err => {
                        if (!err) {
                            console.log('订阅成功:一般通知');
                        }
                    });
                },
                err => {
                    console.log(err);
                }
            );
            this.client.on('message', (topic, message) => {
                if (!userId) {
                    this.clearMqtt();
                    return false;
                }
                let item = JSON.parse(message.toString())
                console.log(topic,item)
                if (item) {
                    this.playAudio(item, topic);
                }
            });
        },
        //清除mqtt连接
        clearMqtt() {
            if (this.client.connected) {
                try {
                    this.client.end();
                    this.client = {
                        connected: false
                    };
                    console.log('Successfully disconnected!');
                } catch (error) {
                    console.log('Disconnect failed', error.toString());
                }
            }
        }
    },
    beforeDestroy() {
        clearInterval(this.timer)
        this.clearMqtt();
    }
};
</script>
<style lang="scss" scoped>
$leftSide: 174px;

.all-container {
    flex-direction: row;
}

.aside-container {
    position: relative;
    flex-shrink: 0;
    width: $leftSide;
    height: calc(100vh - 54px); // position: fixed;
    transition: all 0.25s ease;

    &.hide-bar {
        margin-left: -$leftSide;
    }
}

.main-container {
    flex: 1;
    flex-shrink: 1;
    width: 0;
    height: 100vh; // width: calc(100% - 186px);
    display: flex;
    flex-direction: column;

    .fixed-header {
        position: fixed;
        top: 0;
        right: 0;
        z-index: 996;
        transition: width 0.28s;
        width: calc(100% - $leftSide);

        &~.app-main {
            flex: 1;
            overflow: hidden;
            margin-top: 54px; // padding-top: 54px;
            // min-height: 100vh;
        }
    }

    .paddingBox-container {
        min-height: calc(100vh - 54px - 40px);
    }
}

.hasTag {
    .fixed-header {
        &~.app-main {
            flex: 1;
            overflow: hidden;
        }
    }

    .paddingBox-container {
        min-height: calc(100vh - 176px);
    }
}

.closeSide {
    .aside-container {
        width: 80px;
    }

    .main-container {
        // width: calc(100% - 80px);
        // margin-left: 80px;
    }

    .fixed-header {
        width: calc(100% - 80px);
    }
}

.company-info {
    position: relative;
    height: 28px;
    line-height: 28px;
    font-size: 12px;
    color: #999;
    text-align: center;
    box-shadow: 0 -1px 2px rgba($color: #000000, $alpha: 0.03);
    z-index: 9;
}

.rightPanl {
    right: 1px;
    top: 300px;
    transform: translateY(-50%);
    width: 50px;
    height: 50px;
    color: #fff;
    background: #4165d7;
    border-radius: 6px 0 0 6px;
    text-align: center;
    line-height: 50px;
    font-size: 24px;
    z-index: 999;
}

.app-main {
    height: calc(100vh - 54px);

    &> ::v-deep .scrollbar__wrap .scrollbar__view {
        display: flex;
        flex-direction: column;
        width: 100%;
        min-height: 100%;
        padding: 20px;
        background: #f4faff;
    }
}

//水平布局
.horizontal {
    .horizontal-nav {
        background: #293348;
        color: #f1f1f1;
        height: 54px;
        line-height: 54px;
    }

    .main-container {
        width: 0;
        margin-left: 0;
    }

    .fixed-header {
        width: 100%;
    }

    .nav-user {
        background: #293348;
    }

    .app-main {
        width: 100%;
        box-sizing: border-box;
        background: #f0f2f5;
    }
}
</style>
